package ch12.d1;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;

public class Test2 {
    public static void main(String[] args) throws IOException {
        copy("d:/filetest/png", "d:/filetest/png6");
    }

    public static void copy(String src, String dest) throws IOException {
        Path srcPath = Path.of(src);
        Path destPath = Path.of(dest);
        // 判断是文件还是目录
        if(Files.isDirectory(srcPath)){
            // 如果是目录，就创建目录
            //d:/filetest/png/a-> /a -> d:/filetest/png6/a
            //d:/filetest/png/b
            //d:/filetest/png/b/c1
            //d:/filetest/png/b/c2
            Files.walkFileTree(srcPath, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    // 创建目录
                    //dir: d:/filetest/png/a
                    //src: d:/filetest/png
                    Path r=srcPath.relativize(dir);
                    Path destDir=destPath.resolve(r);
                    if(!Files.exists(destDir))
                        Files.createDirectories(destDir);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    // 创建文件
                    Path r=srcPath.relativize(file);
                    System.out.println(r);
                    Path destFile=destPath.resolve(r);
                    Files.copy(file, destFile);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }
            });

        }else{
            // 如果是文件，就创建文件
            if(!Files.exists(destPath.getParent())){
                Files.createDirectories(destPath.getParent());
            }
            Files.copy(srcPath, destPath);
        }


    }
}
